package cn.leftshine.readme.helper;

import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.FeedException;
import com.rometools.rome.io.SyndFeedInput;
import com.rometools.rome.io.XmlReader;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import cn.leftshine.readme.beans.NewsItem;
import cn.leftshine.readme.event.NewsItemsEvent;

import static cn.leftshine.readme.utils.ImgTool.getImgSrcList;

/**
 * Created by Administrator on 2018/11/2.
 */

public class DataNewsHelper {
    //type： 01 01 01
    //1~2位表示数据源     11为RSS，
    //3~4为表示数据类型    01为News 02为Image
    //5~6位表示子类别
    public final static int TYPE_RSS_ARTICLE        =   110101;
    public final static int TYPE_RSS_IMAGE_SINGLE   =   110201;
    public final static int TYPE_RSS_IMAGE_MULTI    =   110202;
    public final static int TYPE_RSS_IMAGE_ARTICLE  =   110203;    //类似“one一个”此类的数据，第一条为图文，其余为文章

    public static int getType(int type,int begin){
        String typeStr = String.valueOf(type);
        return Integer.parseInt(typeStr.substring(begin,begin+2));
    }

    public static void parseRSS(final String tabTitle, final String rssSrc, final int type) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    SyndFeed feed = new SyndFeedInput().build(new XmlReader(new URL(rssSrc)));
                    List<SyndEntry> entrys =  feed.getEntries();
                    ArrayList<NewsItem> newsItems= new ArrayList<>();
                    for(SyndEntry entry:entrys){
                        ArrayList<String> imgList = getImgSrcList(entry.getDescription().getValue());
                        NewsItem newsItem = new NewsItem(entry,type,imgList);
                        newsItems.add(newsItem);
                    }
                    EventBus.getDefault().post(new NewsItemsEvent(tabTitle,newsItems));

                } catch (FeedException e) {
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
